//
//  MineViewController.m
//  GC_OC
//
//  Created by xyy on 2022/5/23.
//

#import "MineViewController.h"
#import "MineCell.h"
#import "ImportLinkerViewController.h"
#import "FYFileHandle.h"
#import "LoginViewController.h"
#import "Cache.h"
#import "UserModel.h"
#import <JSONModel/JSONModel.h>

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource> {
    NSString *audioSizeStr;
}
@property(nonatomic, strong) UIView *navigationBarView;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *dataSource;
@property(nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) ObjectAFNetWorking* objectAFNet;
@property(nonatomic, strong) NSDictionary *userInfo;
@property(nonatomic, strong) NSIndexPath *currentIndexPath;
@property (nonatomic, weak) UILabel *levelLabel;
@property (nonatomic, weak) UILabel *renewLabel;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的信息";
    self.objectAFNet = [ObjectAFNetWorking new];

    self.dataSource = [NSMutableArray arrayWithArray:@[
                       @[
                       @{@"icon": @"icon收藏", @"name": @"我的收藏", @"rightIcon": @"icon_返回_right"},
                       @{@"icon": @"icon_时长_32_gary", @"name": @"历史记录"},
                       @{@"icon": @"icon_时长_32_gary", @"name": @"搜索记录"},
                       @{@"icon": @"icon_时长_32_gary", @"name": @"学习时长", @"rightIcon": @"icon_删除_default"},
                       @{@"icon": @"icon_播放_96_gary", @"name": @"音频缓存", @"rightIcon": @"icon_删除_default"}
                                                         ],
//                                                       @[@{@"icon": @"icon_外链_32_default", @"name": @"外链导入", @"rightIcon": @"icon_返回_right"},
//                                                        @{@"icon": @"icon_翻译_32_gary备份", @"name": @"文字语音", @"rightIcon": @"icon_返回_right"},
//                                                        @{@"icon": @"ttswenzizhuanyuyin1", @"name": @"文字翻译", @"rightIcon": @"icon_返回_right"}]
    ]];
        
    [self setupUIView];
    [self getUserInfo];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:true];
    
    //计算缓存音频
//    NSString * cacheFolderPath = [[NSHomeDirectory( ) stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"MusicCaches"];
//    NSInteger size = [FYFileHandle getSizeOfFilePath:cacheFolderPath];
//    audioSizeStr = [FYFileHandle axcFileSizeWithToString:size];
//    if ([audioSizeStr isEqualToString:@"0 B"]) {
//        audioSizeStr = @"";
//    }
    audioSizeStr = [self calculateAudioSize];
    
    [self.tableView reloadData];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:true];
}

- (void)getUserInfo {
    UserModel *userModel = [FKCacheTool userInfo];
    if (userModel) {
        NSDictionary *dic = [userModel toDictionary];
        [self refreshUI:dic];
    } else {
        NSDictionary *info = [[NSUserDefaults standardUserDefaults] valueForKey:@"bnyt_userInfo"];
        NSError *err;
        UserModel *user = [[UserModel alloc] initWithDictionary:info error:&err];
        [Cache shared].userInfo = user;
        if (info.count != 0) {
            //先加载本地
            [self refreshUI:info];
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

- (void)refreshUI:(NSDictionary *) dic {
    NSDictionary *userinfo = dic[@"userinfo"];
    self.userInfo = userinfo;
    
    //账号
    UILabel *account = (UILabel *)[self.headerView viewWithTag:1001];
    account.text = [NSString stringWithFormat:@"账号：%@",userinfo[@"username"]];
    
    //注册时间
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.dateFormat = @"yyyy年MM月dd日";
    UILabel *registerDate = (UILabel *)[self.headerView viewWithTag:1002];
    NSInteger createtime = [(NSNumber *)userinfo[@"jointime"] integerValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:createtime];
    registerDate.text = [NSString stringWithFormat:@"注册时间：%@",[dateFormatter stringFromDate:date]];
    
    //到期时间
    UILabel *expireDate = (UILabel *)[self.headerView viewWithTag:1003];
    id endtime = userinfo[@"endtime"];
    if ([endtime isEqualToString:@""]) {
        NSString *loginTime = fkFORMAT(@"%@", userinfo[@"logintime"]);
        loginTime = [loginTime fk_timeWithFormat:@"yyyy年MM月dd日"];
        expireDate.text = fkFORMAT(@"近期登录: %@", loginTime);
    } else {
        NSInteger time = [(NSNumber *)userinfo[@"endtime"] integerValue];
        NSDate *expire = [NSDate dateWithTimeIntervalSince1970:time];
        
        BOOL isExpire = NO;
        if ([expire compare:[NSDate date]] != NSOrderedDescending) {
            isExpire = YES;
        } else {
            NSTimeInterval time = [expire timeIntervalSinceDate:[NSDate date]];
            if (time > 0 && time <= (3600 * 24 * 3)) {
                isExpire = YES;
            }
        }
        
        
        NSString *str = [NSString stringWithFormat:@"到期时间：%@",[dateFormatter stringFromDate:expire]];
        NSString *nameStr2 = [dateFormatter stringFromDate:expire];

        //先查找分段样式文字的range
        NSRange range2 = [str rangeOfString:nameStr2];

        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];

        //分段文字的颜色
        [attri addAttribute:NSForegroundColorAttributeName value:XHUIColorFromRGB(0x0091FF) range:range2];
        if (isExpire == YES) {
            [attri addAttribute:NSForegroundColorAttributeName value:XHUIColorFromRGB(0xff0000) range:range2];
        }
        expireDate.attributedText = attri;
    }
    
    //会员等级
    NSDictionary *vipInfo = dic[@"vipInfo"];
    NSString *level = vipInfo[@"level"];
    if ([level isEqualToString:@"0"]) { // 普通用户
        self.levelLabel.hidden = false;
        self.renewLabel.hidden = true;
        self.levelLabel.text = [NSString stringWithFormat:@"等级：%@", vipInfo[@"name"]];
    } else { // 会员
        self.levelLabel.hidden = true;
        self.renewLabel.hidden = false;
    }
//    self.levelLabel.text = @"";
//    NSString *name = [vipInfo valueForKey:@"name"];
//
//    if (name.length != 0) {
//        self.levelLabel.text = [NSString stringWithFormat:@"等级：%@", name];
//    }
    
    // 把userInfo里面返回的收藏信息删除，不然用NSUserDefaults缓存的时候会闪退
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
    dict[@"collect"] = nil;
    [[NSUserDefaults standardUserDefaults] setValue:dict forKey:@"bnyt_userInfo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)setupUIView {
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.navigationBarView];
    
    UILabel *naviTitle = [UILabel new];
    naviTitle.text = @"我的";
    naviTitle.textAlignment = NSTextAlignmentCenter;
    naviTitle.textColor = [UIColor blackColor];
    naviTitle.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
    [self.navigationBarView addSubview:naviTitle];
    
    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"icon_返回_32_left"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    
    UIButton *exitButton = [UIButton new];
    [exitButton setImage:[UIImage imageNamed:@"icon_退出_32_default备份"] forState:UIControlStateNormal];
    [exitButton addTarget:self action:@selector(exitAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:exitButton];
    
    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 50;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[MineCell class] forCellReuseIdentifier:@"MineCell"];
    
    // 底部用于显示版本号的label
    NSString *version = fkFORMAT(@"version %@", [UIApplication sharedApplication].fk_appVersion);
    UILabel *versionLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor999999 textAlignment:NSTextAlignmentCenter text:version];
//    versionLabel.frame = CGRectMake(0, 0, fkScreenW, 40);
//    self.tableView.tableFooterView = versionLabel;
    [self.view addSubview:versionLabel];
    
    __weak typeof(self) ws = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [ws getUserInfo];
    }];
    
    self.headerView = [UIView new];
    self.headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 130);
    self.headerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = self.headerView;
    
    UILabel *account = [UILabel new];
    account.text = @"账号：";
    account.tag = 1001;
    account.textColor = [UIColor blackColor];
    account.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
    [self.headerView addSubview:account];
    
    UIButton *copyButton = [UIButton new];
    [copyButton setImage:[UIImage imageNamed:@"icon_复制_32_default"] forState:UIControlStateNormal];
    [copyButton addTarget:self action:@selector(copyAction) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:copyButton];
    
    UILabel *registerDate = [UILabel new];
    registerDate.text = @"注册时间：";
    registerDate.tag = 1002;
    registerDate.textColor = XHUIColorFromRGB(0x6D7278);
    registerDate.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.headerView addSubview:registerDate];
    
    UILabel *expireDate = [UILabel new];
    expireDate.textColor = XHUIColorFromRGB(0x6D7278);
    NSString *str = @"到期时间";
    NSString *nameStr2 = @"";
    //先查找分段样式文字的range
    NSRange range2 = [str rangeOfString:nameStr2];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
    //分段文字的颜色
    [attri addAttribute:NSForegroundColorAttributeName value:XHUIColorFromRGB(0x0091FF) range:range2];
    expireDate.attributedText = attri;
    expireDate.tag = 1003;
    expireDate.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.headerView addSubview:expireDate];
    
    UILabel *level = [UILabel new];
    level.text = @"等级：普通会员";
    level.tag = 1004;
    level.textColor = [UIColor blackColor];
    level.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.headerView addSubview:level];
    self.levelLabel = level;
    
    UILabel *renewLabel = [UILabel fk_labelWithFont:fk_adjustFont(16) textColor:UIColor.whiteColor textAlignment:NSTextAlignmentCenter text:@"续"];
    [self.headerView addSubview:renewLabel];
    self.renewLabel = renewLabel;
    renewLabel.backgroundColor = fkMainColor;
    [renewLabel fk_viewCornerRadius:14 borderWidth:0 borderColor:nil];
    [renewLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(renewLabelDidTap)]];
    renewLabel.hidden = true; // 设置默认隐藏
    
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        CGFloat height = NAVI_BAR_HIGHT;
        if ([self isFullScreenIphone]){
            
            height += 34;
        }
        make.height.mas_equalTo(height);
    }];
    [naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.centerX.equalTo(self.navigationBarView);
        make.top.mas_equalTo(StatusBarHeight);
        make.height.mas_equalTo(40);
    }];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.view).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.right.equalTo(self.view).offset(-12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBarView.mas_bottom).offset(0);
        make.left.right.bottom.equalTo(self.view);
    }];
    [account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.lessThanOrEqualTo(@300);
        make.left.equalTo(self.headerView).offset(16);
        make.height.mas_equalTo(20);
        make.top.mas_equalTo(31);
    }];
    [copyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(account.mas_right).offset(30);
        make.height.width.mas_equalTo(24);
        make.centerY.equalTo(account);
    }];
    [registerDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(account);
        make.top.equalTo(account.mas_bottom).offset(5);
        make.height.width.mas_equalTo(18);
        make.right.equalTo(self.headerView);
    }];
    [expireDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(account);
        make.top.equalTo(registerDate.mas_bottom).offset(5);
        make.height.width.mas_equalTo(18);
        make.right.equalTo(self.headerView);
    }];
    [level mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.lessThanOrEqualTo(@300);
        make.centerY.equalTo(expireDate);
        make.height.mas_equalTo(18);
        make.right.equalTo(self.headerView).offset(-6);
    }];
    [renewLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(28);
        make.centerY.equalTo(expireDate);
        make.right.offset(-50);
    }];
    [versionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(-fkOffsetBottom);
        make.height.offset(40);
    }];
}
- (void)back {
    if (self.navigationController.viewControllers.count == 1) {
        [self.navigationController dismissViewControllerAnimated:true completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
//    NSHomeDirectory()
    
    if (self.navigationController.viewControllers.count == 1) {
        if ([ICMusicPlayManager sharedManager].narrowView) {
            [ICMusicPlayManager sharedManager].narrowView.frame = CGRectMake(0, SCREEN_HEIGHT - 50 - GCtabbarHeight, SCREEN_WIDTH, 50);
        }
    }
}

#pragma mark - action
- (void)exitAction {
    NSString * path = [[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] stringByAppendingPathComponent:@"MusicTemp.mp4"];
    NSLog(@"====%@",path);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认退出登录?" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[Cache shared] removeUser_id];
        [FKCacheTool logout];
        [self.navigationController popViewControllerAnimated:YES];
        [SVProgressHUD showSuccessWithStatus:@"退出登录成功"];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
//    [self.view makeToast:@"登陆功能暂未开发"];
}

- (void)renewLabelDidTap
{
    // 预留的点击续费通道
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = self.dataSource[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineCell"];
    
    NSArray *array = self.dataSource[indexPath.section];
    NSDictionary *info = array[indexPath.row];
    cell.info = info;
    
    cell.leftIcon.image = [UIImage imageNamed:[info valueForKey:@"icon"]];
    cell.name.text = [info valueForKey:@"name"];
    [cell.rightIcon setImage:[UIImage imageNamed:[info valueForKey:@"rightIcon"]] forState:UIControlStateNormal];
    
    cell.detail.text = @"";
    
    cell.switchBtn.hidden = true;
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            cell.switchBtn.hidden = false;
            cell.switchBtn.on = [FKCacheTool isOpenHistoryRecord];
        } else if (indexPath.row == 2) {
            cell.switchBtn.hidden = false;
            cell.switchBtn.on = [FKCacheTool isOpenSearchRecord];
        } else if (indexPath.row == 3) { // 学习时长
            NSInteger cc = [SUPlayerManager manager].accumulateCount;
            cell.detail.text = [self timeFormatted:cc];
        } else if (indexPath.row == 4) { // 音频缓存
            cell.detail.text = audioSizeStr;
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.detail.text = @"可批量导入";
        }
    }
    
    
//    if (indexPath.section == 0 && indexPath.row == 0) {
//
//    } else if (indexPath.section == 0 && indexPath.row == 1) {
//        NSInteger cc = [SUPlayerManager manager].accumulateCount;
//        cell.detail.text = [self timeFormatted:cc];
//    } else if (indexPath.section == 0 && indexPath.row == 2) {
//        cell.detail.text = audioSizeStr;
//    } else if (indexPath.section == 1 && indexPath.row == 0) {
//        cell.detail.text = @"可批量导入";
//    }
    
    cell.rightBlock = ^(NSDictionary * _Nonnull info) {
        if ([info[@"name"] isEqualToString:@"音频缓存"]) {
            [self clearAudioCache];
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell.contentView layoutIfNeeded];
    MineCell *mine = (MineCell *)cell;
    mine.contentView.layer.mask = nil;

    if ((indexPath.section == 0 && indexPath.row == 2) || (indexPath.section == 1 && indexPath.row == 2)) {
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:mine.contentView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(30, 30)];
        CAShapeLayer *layer = [CAShapeLayer new];
        layer.frame = mine.contentView.bounds;
        layer.path = path.CGPath;
        mine.contentView.layer.mask = layer;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
    view.backgroundColor = [UIColor clearColor];
    
    UIView *container = [UIView new];
    container.backgroundColor = XHUIColorFromRGB(0xE2F2FF);
    [view addSubview:container];
    
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(view);
    }];
    
    [view layoutIfNeeded];
    container.layer.mask = nil;

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:container.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(30, 30)];
    CAShapeLayer *layer = [CAShapeLayer new];
    layer.frame = container.bounds;
    layer.path = path.CGPath;
    container.layer.mask = layer;
    
    UIImageView *imageView = [UIImageView new];
    imageView.image = [UIImage imageNamed:@"iconine"];
    [container addSubview:imageView];
    
    UILabel *title = [UILabel new];
    title.text = section == 0 ? @"设置" : @"小工具";
    title.textColor = [UIColor blackColor];
    title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold];
    [container addSubview:title];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(33, 30));
        make.left.mas_equalTo(12);
        make.centerY.equalTo(container);
    }];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(120, 30));
        make.left.equalTo(imageView.mas_right).offset(5);
        make.centerY.equalTo(container);

    }];
    
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    self.currentIndexPath = indexPath;
    [self.tableView reloadData];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            CollectController *ccVC = [CollectController new];
            [self.navigationController pushViewController:ccVC animated:YES];
        }else if(indexPath.row == 1){
            
        }else if(indexPath.row == 2){

        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController pushViewController:[ImportLinkerViewController new] animated:YES];
                self.currentIndexPath = nil;
            });
        }else if(indexPath.row == 1){
            
        }else if(indexPath.row == 2){
            
        }
    }
}


- (void)deleteFilePath
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error];
    if (error) {    // 处理错误
        
    } else {
        for (NSString *file in files) {
            if ([file containsString:@".mp3"]) {
                NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
                BOOL success = [fileManager removeItemAtPath:path error:&error];
                if (!success) {
                    // 处理错误
                    break;
                }
            }
        }
    }
}

- (NSString *)calculateAudioSize
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error];
    NSMutableArray *needCalculateArr = [NSMutableArray array];
    if (error) {
        
    } else {
        for (NSString *file in files) {
            if ([file containsString:@".mp3"]) {
                NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
                [needCalculateArr addObject:path];
            }
        }
    }
    
    unsigned long long totalSize = 0;
    for (NSString *filePath in needCalculateArr) {
        NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
        unsigned long long fileSize = [fileSizeNumber unsignedLongLongValue];
        totalSize += fileSize;
    }
    
    return [self convertFileSize:totalSize];
}

- (NSString *) convertFileSize:(long long)size {
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1f GB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f MB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f MB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f KB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f KB", f];
        }
    } else
        return [NSString stringWithFormat:@"%lld B", size];
}

- (void)copyAction {
    if ([self.userInfo valueForKey:@"username"]) {
        [UIPasteboard generalPasteboard].string = [self.userInfo valueForKey:@"username"];
        [self.view makeToast:@"复制成功"];
    }
}

- (void)clearAudioCache {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定清空音频缓存?" message:nil preferredStyle: UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteFilePath];
        self->audioSizeStr = @"0 B";
        [self.tableView reloadData];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];

    [self presentViewController:alert animated:YES completion:nil];
}

-(BOOL)isFullScreenIphone {
    BOOL isFullIphone = NO;
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            isFullIphone = YES;
        }
    }
    return isFullIphone;
}

- (NSString *)timeFormatted:(int)totalSeconds
{
    if (totalSeconds == 0) return @"0分";
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    return [NSString stringWithFormat:@"%02d小时%02d分",hours, minutes];
}
@end
